package cn.ygh.bbo.system.sdk.aspect;

import cn.ygh.bbo.common.annotation.DataScope;
import cn.ygh.bbo.common.utils.StringUtils;
import cn.ygh.bbo.framerwork.core.BaseEntity;
import cn.ygh.bbo.system.bean.Admin;
import cn.ygh.bbo.system.sdk.shiro.ShiroUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ygh
 * @Desc 数据权限切面
 * @date 2019/11/26
 */
@Aspect
public class DataScopeAspect {

    private final Logger logger=LoggerFactory.getLogger(getClass());

    /**
     * 织入点
     */
    @Pointcut("@annotation(cn.ygh.bbo.common.annotation.DataScope)")
    public void dataScopePointCut() {}

    @Before("dataScopePointCut()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        DataScope dataScope = getAnnotationDataScope(joinPoint);
        if (dataScope==null){
            return;
        }
        Admin admin=ShiroUtils.getPrincipal();
        if (admin==null){
            return;
        }
        //约定第一个参数
        BaseEntity baseEntity = (BaseEntity) joinPoint.getArgs()[0];
        if (baseEntity==null){
            return;
        }
        //数据权限表名获取
        String tableName=baseEntity.getClass().getSimpleName();
        Map<String,String>dataFilters=admin.getDataFilters();
        if (dataFilters==null){
            return;
        }
        String sql=dataFilters.get(tableName);
        //过滤字段添加
        if (org.apache.commons.lang3.StringUtils.isNotBlank(sql)){
            Map<String,Object>params=new HashMap<>();
            params.put("sessionObj",admin);
            sql = StringUtils.getGroovyResult(sql, params);
            baseEntity.setDataScope(sql);
        }

    }

    /**
     * 是否存在注解，如果存在就获取
     */
    private DataScope getAnnotationDataScope(JoinPoint joinPoint) throws Exception {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        if (method != null) {
            return method.getAnnotation(DataScope.class);
        }
        return null;
    }


}
